package com.lzc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lzc.common.ImCache;
import com.lzc.mapper.FriendMapper;
import com.lzc.mapper.UserMapper;
import com.lzc.pojo.dto.UserDto;
import com.lzc.pojo.entity.Friend;
import com.lzc.pojo.entity.User;
import com.lzc.pojo.vo.Result;
import com.lzc.service.FriendService;
import com.lzc.util.ThreadLocalUtil;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.lzc.util.RedisKey.FRIEND_APPLY_KEY;

@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private ImCache cache;

    @Autowired
    private UserMapper userMapper;

    /**
     * 找到所有朋友
     * @return
     */
    @Override
    public Result findAllFriends() {
        Long id = ThreadLocalUtil.getUid();
        // 获取所有用户id
        List<Long> friendIds = friendMapper.findFriends(id);
        if (CollectionUtil.isEmpty(friendIds)){
            return Result.OK(null);
        }
        List<User> friends = userMapper.selectList(new LambdaQueryWrapper<User>().in(User::getId, friendIds));
        // 所有用户消息->用户DTO
        List<UserDto> friendDtos = friends.stream().map(UserDto::new).collect(Collectors.toList());

        return Result.OK(friendDtos);
    }

    /**
     * 向指定id的用户发起好友申请 TODO 后续可改成redis
     * @param uid
     * @return
     */
    @Override
    public Result applyFriend(Long uid) {
        // 获取当前用户id
        Long id = ThreadLocalUtil.getUid();
        // 将当前用户id存入对方的缓存好友申请集合中
        List list = cache.getList(FRIEND_APPLY_KEY + uid);
        if (list == null || list.isEmpty()){
            List<Long> ids = new ArrayList<>();
            ids.add(id);
            cache.set(FRIEND_APPLY_KEY + uid , ids);
            return Result.OK(null);
        }
        list.add(id);
        cache.set(FRIEND_APPLY_KEY + uid , list);
        return Result.OK(null);
    }

    /**
     * 展示所有好友申请
     * @return 用户dto列表
     */
    @Override
    public Result showAllApply() {
        // 获取当前用户id
        Long id = ThreadLocalUtil.getUid();
        // 获取申请好友集合
        List<Long> friendIds = cache.getList(FRIEND_APPLY_KEY + id);
        if (friendIds == null || friendIds.isEmpty()){
            return Result.OK(null);
        }
        // 获取好友信息
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().in(
                User::getId, friendIds
        ));
        // user -> userDto
        List<UserDto> dtos = users.stream().map(UserDto::new).collect(Collectors.toList());
        return Result.OK(dtos);
    }

    /**
     * 添加为好友
     * @param uid 好友id
     * @return
     */
    @Override
    @Transactional
    public Result addFriendById(Long uid) {
        synchronized (uid.toString().trim()){
            // 获取当前用户id
            Long id = ThreadLocalUtil.getUid();
            // 判断好友id是否在好友申请集合中
            List<Long> list = cache.getList(FRIEND_APPLY_KEY + id);
            if (list == null || !list.contains(uid)){
                return Result.FILE("对方未申请加你为好友！！");
            }
            list.remove(uid);
            // 如果集合为空则直接清除key
            if (list.isEmpty()){
                cache.remove(FRIEND_APPLY_KEY + id);
            }else {
                cache.set(FRIEND_APPLY_KEY + id,list);
            }
            // 添加好友
            Friend friend = new Friend(id,uid);
            friendMapper.insert(friend);
            friend.setId(null);
            friend.setUserId(uid);
            friend.setFriendId(id);
            friendMapper.insert(friend);
            return Result.OK(null);
        }
    }

    /**
     * 判断是否为好友
     * @param uid
     * @return
     */
    @Override
    public Result isFriend(Long uid) {
        // 获取当前用户id
        Long id = ThreadLocalUtil.getUid();
        Friend friend = friendMapper.isFriend(id, uid);
        if (friend == null){
            return Result.OK(false);
        }
        return Result.OK(true);
    }


}
